<template>
  <el-form
    :model="userForm"
    :rules="rules"
    ref="userForm"
    label-width="100px"
    class="baseInfo-form"
  >
    <el-form-item label="用户姓名" prop="userName">
      <el-input v-model.trim="userForm.userName" size="large" />
    </el-form-item>
    <el-form-item label="手机号码" prop="phonenumber">
      <el-input v-model.trim="userForm.phonenumber" size="large" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model.trim="userForm.email" size="large" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('userForm')">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updateUser } from "@/api/user";
import { mapGetters } from "vuex";
export default {
  computed: {
    ...mapGetters(["userInfo"]),
  },
  data() {
    return {
      rules: {
        userName: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
        ],
        phonenumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱地址",
            trigger: "blur",
          },
          {
            type: "email",
            message: "请输入正确的邮箱",
            trigger: ["blur"],
          },
        ],
      },
      userForm: {},
    };
  },
  mounted() {
    if (this.userInfo) {
      this.userForm = { ...this.userInfo };
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            userName: this.userForm.userName,
            phonenumber: this.userForm.phonenumber,
            email: this.userForm.email,
          };
          updateUser(params)
            .then((res) => {
              if (res.code == 0) {
                this.$message.success("修改成功");
                const updatedUserInfo = {
                  ...this.userInfo,
                  userName: this.userForm.userName,
                  phonenumber: this.userForm.phonenumber,
                  email: this.userForm.email,
                };
                this.$store.commit("user/SET_USER_INFO", updatedUserInfo);
                this.$store.commit("user/SET_USERNAME", this.userForm.userName);
              }
            })
            .catch((err) => {
              console.log(err, "失败");
            });
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style lang="scss">
.baseInfo-form {
  .el-form-item {
    margin-bottom: 25px;
  }
}
</style>
